package com.lanhai.utils;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.lanhai.MainAction;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
/**
 * 监听UDP端口
 * @author liangmin
 *
 */
public class UDPListener4Json extends Thread {
	
	private DatagramPacket dp;
	private DatagramSocket ds;
	private MainAction mainAction;
	private int port;
	
	public UDPListener4Json(MainAction mainAction, int port){
		this.mainAction = mainAction;
		this.port = port;
	}
	
	public void run() {
		try{
			byte buf[] = new byte[10240];
			dp = new DatagramPacket(buf, buf.length);
			ds = new DatagramSocket(port);
			while(true){
				ds.receive(dp);
				
	            String receStr = new String(dp.getData(), 0 , dp.getLength(), "UTF-8");
	            //列表
	            //JSONArray jarray = JSONArray.fromObject(receStr);
	            JSON json = JSONObject.fromObject(receStr);
	            mainAction.saveData(json);
	            //JSONObject json = JSONObject.fromObject(jarray.get(0));
			}	
		}catch(Exception e){
			e.printStackTrace();
		}	
	}
}
